/**
 * 北京钉图互动科技 all right reserver
 */
package com.sincebest.fivestar.common.exception.support;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.sincebest.fivestar.common.exception.ErrorResponse;
import com.sincebest.fivestar.common.jackson.QuietObjectMapper;

/**
 * 重载替换Spring Boot默认的BasicErrorController, 增加日志并让错误返回方式统一.
 * 
 * @author Wangyi
 * @since 2016年6月8日
 */
@Controller
public class ErrorPageController implements ErrorController {

	private static Logger logger = LoggerFactory.getLogger(ErrorPageController.class);

	@Value("${error.path:/error}")
	private String errorPath;
	@Autowired
	private QuietObjectMapper objectMapper;

	private ErrorAttributes errorAttributes = new DefaultErrorAttributes();

	@RequestMapping(value = "${error.path:/error}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public ErrorResponse handle(HttpServletRequest request) {
		Map<String, Object> attributes = getErrorAttributes(request);

		attributes.put("from", request.getRemoteAddr());
		logger.error(objectMapper.toJson(attributes));

		return new ErrorResponse(attributes.get("status").toString(), attributes.get("error").toString());
	}

	private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
		RequestAttributes requestAttributes = new ServletRequestAttributes(request);
		return this.errorAttributes.getErrorAttributes(requestAttributes, false);
	}

	@Override
	public String getErrorPath() {
		return this.errorPath;
	}
}
